<script setup>
import {get} from "../../js/http.js";
import {onMounted, ref, reactive} from 'vue';
import {toCamelCase} from "../../js/common.js";

const emit = defineEmits(['close', 'save'])
const analyzerTypes = ref(["smartcn","jcseg", "ik", "simple", "whitespace"])
let cronTip = ref("")

let indexRoot = ref("./lucene")

const props = defineProps({
  currentIndex: {
    type: Object,
    required: true
  },
  dbInfo: {
    type: Object,
    required: true
  },
});

onMounted(async () => {
  await getSchemaConn();
  if (props.currentIndex.conn) {
    await getDatabase(props.currentIndex.conn)
  }
  if (props.currentIndex.database) {
    await getSchemaTable(props.currentIndex.conn, props.currentIndex.database)
  }
  if (props.currentIndex.table) {
    await getSchemaField(props.currentIndex.conn, props.currentIndex.database, props.currentIndex.table)
  }
})

async function getSchemaConn() {
  if(checkHasConn() == true){
    return
  }
  let url = "/admin/setting/getSchema";
  await get(url).then(res => {
    res.result.data.forEach(item => {
      props.dbInfo[item.connName] = item;
      props.dbInfo[item.connName]["dbs"] = {}
    });
  })
  .catch(error => console.log(error))
}
async function getDatabase(conn) {
  if(checkHasDatabase()  == true ){
    return
  }
  let url = "/admin/setting/getSchema";
  await get(url,{conn: conn}).then(res => {
    props.dbInfo[conn]["dbs"] = res.result.data
  })
  .catch(error => console.log(error))
}

async function getSchemaTable(conn,database) {
  if (!conn) {
    return
  }
  if(checkHasTable()  == true){
    return
  }
  let url = "/admin/setting/getSchema";
  let res = await get(url, {conn: conn ,database: database })
  props.dbInfo[conn]["dbs"][database]["tableMap"] = res.result.data
}

async function getSchemaField(conn,database, table) {
  if(checkHasField()  == true ){
    return
  }
  let url = "/admin/setting/getSchema";
  let res = await get(url, {conn: conn, database: database, table: table})
  props.dbInfo[conn]["dbs"][database]["tableMap"][table]["columnsMap"] = res.result.data;
}

function cronCheck(e) {
  if (e.target.value.length > 0) {
    get("/admin/task/checkCron", {cron: e.target.value}).then(res => {
      if (res.success) {
        cronTip.value = res.result
      } else {
        cronTip.value = res.message
      }
    }).catch(error => console.log(error))
  }
}

function handleConn(e) {
  if (e.target.selectedIndex == 0) {
    props.currentIndex.conn = "";
    return;
  }
  getDatabase(e.target.value)
}

function handleDatabase(e) {
  if (e.target.selectedIndex == 0) {
    props.currentIndex.database = "";
    return;
  }
  getSchemaTable(props.currentIndex.conn,props.currentIndex.database)
}
function handleTable(e) {
  if (e.target.selectedIndex == 0) {
    return;
  }
  if ( props.currentIndex.name  ==  "NewIndex"){
    props.currentIndex.name = toCamelCase(props.currentIndex.table)
  }
  getSchemaField(props.currentIndex.conn,props.currentIndex.database, e.target.value)
}

function checkHasConn() {
  try {
    return Object.keys(props.dbInfo).length>0 ?true : false
  } catch (error) {
    return  false
  }
}
function checkHasDatabase() {
  try {
    return Object.keys(props.dbInfo[props.currentIndex.conn]['dbs']).length > 0 ? true : false
  } catch (error) {
    return  false
  }
}
function checkHasTable( ) {
  try {
    return Object.keys(props.dbInfo[props.currentIndex.conn]['dbs'][props.currentIndex.database]["tableMap"]).length > 0 ? true : false
  } catch (error) {
    return  false
  }
}
function checkHasField() {
  try {
    return Object.keys(props.dbInfo[props.currentIndex.conn]['dbs'][props.currentIndex.database]["tableMap"][props.currentIndex.table]['columnsMap']).length > 0 ? true : false
  } catch (error) {
    return  false
  }
}


</script>

<template>
  <div class="modal is-active">
    <div class="modal-background"></div>
    <div style="width:600px;" class="modal-card">
      <header class="modal-card-head">
        <p class="modal-card-title">索引设置</p>
        <button aria-label="close" class="delete" @click="emit('close')"></button>
      </header>
      <section class="modal-card-body">
        <!--索引设置 Begin-->
        <div class="field">
          <label class="label">备注名</label>
          <div class="control">
            <input v-model="currentIndex.remark" class="input is-link" placeholder="Index Remark Name" type="text">
          </div>
          <span class="help is-success">索引的说明</span>
        </div>
        <div class="field">
          <label class="label">是否基于数据库</label>
          <div class="control is-expanded">
            <div class="select is-fullwidth is-link">
              <select v-model="currentIndex.dbBase">
                <option :value="true">是</option>
                <option :value="false">否</option>
              </select>
            </div>
          </div>
        </div>
        <label class="label" v-if="currentIndex.dbBase == true">选择数据源、数据库、数据表</label>
        <div class="field is-grouped" v-if="currentIndex.dbBase == true">
          <div class="control" style="max-width: 160px">
            <div class="select is-fullwidth is-link">
              <select v-model="currentIndex.conn" @change="handleConn">
                <option>选择数据源</option>
                <option v-for="(value,key) in dbInfo" v-if="dbInfo" :value="key">{{ key }}</option>
              </select>
            </div>
          </div>
          <div class="control"  style="max-width: 160px">
            <div class="select  is-link">
              <select v-model="currentIndex.database" @change="handleDatabase">
                <option>选择数据库</option>
                <option v-for="(value,key) in dbInfo[currentIndex.conn]['dbs']" v-if="checkHasDatabase()==true" :value="key">{{ key }}</option>
              </select>
            </div>
          </div>
          <div class="control"  style="max-width: 160px">
            <div class="select is-link">
              <select v-model="currentIndex.table" @change="handleTable">
                <option>选择表名</option>
                <option v-for="(value,key) in dbInfo[currentIndex.conn]['dbs'][currentIndex.database]['tableMap']"
                        v-if="checkHasTable() == true" :value="key">
                  {{ key }}
                </option>
              </select>
            </div>
          </div>
        </div>

        <div class="field">
          <label class="label">索引名称</label>
          <div class="control">
            <input v-model="currentIndex.name" :disabled="currentIndex.id ? true : false" class="input is-link" placeholder="Index Folder Name On Disk"
                   type="text">
          </div>
          <span class="help is-success">索引名称只能是英文</span>
        </div>
        <div class="field">
          <label class="label">索引目录</label>
          <div class="control">
            <input v-model="currentIndex.path"  class="input is-link" placeholder="Index Folder Name On Disk" type="text">
          </div>
          <div class="tags has-addons mt-2">
            <span class="tag is-dark">索引根目录</span>
            <span class="tag is-info">{{ indexRoot }}</span>
          </div>

        </div>
        <div class="field">
          <label class="label">索引类型</label>
          <div class="control is-expanded">
            <div class="select is-fullwidth is-link">
              <select v-model="currentIndex.type" @change="handleConn">
                <option value="normal">Normal</option>
                <option value="facet">Facet</option>
              </select>
            </div>
          </div>
          <span class="help is-success">Facet模式主要用数据统计分析钻取等功能</span>
        </div>

        <div class="field">
          <label class="label">目录类型</label>
          <div class="control is-expanded">
            <div class="select is-fullwidth is-link">
              <select v-model="currentIndex.fsdType">
                <option value="nio">NIOFSDirectory</option>
                <option value="mmap">MMapDirectory</option>
              </select>
            </div>
          </div>
          <span
              class="help is-success">MMapDirectory模式性能更好，但是需要配置内存，如果内存不够，请使用NIOFSDirectory模式</span>
        </div>

        <div class="field"  v-if="currentIndex.dbBase == true">
          <label class="label">索引字段</label>
          <div class="control">
            <input v-model="currentIndex.fields" class="input is-link" placeholder="*" type="text">
          </div>
          <span class="help is-success">索引所有的字段是使用 * ，部分字段用逗号隔开</span>
        </div>
        <div class="field">
          <label class="label">关键字段</label>
          <div class="control is-expanded">
            <div class="select is-fullwidth is-link"  v-if="currentIndex.dbBase == true">
              <select v-model="currentIndex.key" >
                <option>选择字段</option>
                <option v-for="fieldItem in dbInfo[currentIndex.conn]['dbs'][currentIndex.database]['tableMap'][currentIndex.table]['columnsMap']"
                        v-if="checkHasField()==true"
                        :value="fieldItem.columnName">{{ fieldItem.columnName }}({{ fieldItem.originalType }})
                </option>
              </select>
            </div>
            <div v-else>
              <input v-model="currentIndex.key" class="input is-link" placeholder="*" type="text">
            </div>
          </div>
          <span class="help is-success">表的主键字段</span>
        </div>
        <div class="field">
          <label class="label">分词器</label>
          <div class="control is-expanded">
            <div class="select is-fullwidth is-link">
              <select v-model="currentIndex.analyzer">
                <option v-for="item in analyzerTypes" :value="item">{{ item }}</option>
              </select>
            </div>
          </div>
          <span class="help is-success">涉及中文模糊搜索的选择ik分词器</span>
        </div>
        <div class="field"  v-if="currentIndex.dbBase == true">
          <label class="label">CDC任务</label>
          <div class="control is-expanded">
            <div class="select is-fullwidth is-link">
              <select v-model="currentIndex.cdc">
                <option value="true"> 接收来自CDC的数据</option>
                <option value="false"> 不接受CDC数据</option>
              </select>
            </div>
          </div>
          <span class="help is-success">表的主键字段</span>
        </div>
        <div class="field"  v-if="currentIndex.dbBase == true">
          <label class="label">重建任务</label>
          <div class="control">
            <input v-model="currentIndex.cron" class="input is-link" placeholder="Cron Text，eg：0 0 2 1 * ? *"
                   type="text" @input="cronCheck">
          </div>
          <span class="help is-success">Cron表达式:{{ cronTip }}</span>
        </div>
        <!--索引设置 End-->
      </section>
      <footer class="modal-card-foot is-flex is-justify-content-flex-end">
          <button class="button is-link" @click="emit('save')">保存</button>
      </footer>
    </div>
  </div>
</template>

<style scoped>

</style>